package com.shopping.mall.core.module.goods.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shopping.mall.auth.annotation.UnLogin;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.core.module.goods.entity.Goods;
import com.shopping.mall.core.module.goods.entity.RecommendGoods;
import com.shopping.mall.core.module.goods.mapper.GoodsMapper;
import com.shopping.mall.core.module.specialValue.entity.SpecialValue;
import com.shopping.mall.core.module.specialValue.mapper.SpecialValueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/goods/recommend")
public class RecommendController {

    @Autowired
    private SpecialValueMapper specialValueMapper;

    @Autowired
    private GoodsMapper goodsMapper;


    @PostMapping
    public Result<Object> edit(@RequestBody RecommendGoods recommendGoods){
        specialValueMapper.saveRecommendGoods(JSON.toJSONString(recommendGoods.getIds()));
        return Result.OK();
    }


    @UnLogin
    @GetMapping
    public Result<Object> get(){
        QueryWrapper<SpecialValue> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("recommend_goods");
        SpecialValue goodsJson=specialValueMapper.selectOne(queryWrapper);
        List<String> ids= JSONArray.parseArray(goodsJson.getRecommendGoods(),String.class);
        if(ids==null||ids.size()==0){
            return Result.OK();
        }
        QueryWrapper<Goods> goodsQueryWrapper=new QueryWrapper<>();
        goodsQueryWrapper.in("id",ids);
        List<Goods> goods=goodsMapper.selectList(goodsQueryWrapper);
        Map<String,Goods> goodsMap=new HashMap<>();
        if(goods!=null&&goods.size()>0){
            for(Goods goodsNode:goods){
                goodsMap.put(goodsNode.getId(),goodsNode);
            }
        }
        List<Goods> goodsList=new ArrayList<>();
        for(String id:ids){
            goodsList.add(goodsMap.get(id));
        }
        return Result.OK(goodsList);
    }

    @PostMapping("/add")
    public Result<Object> add(@RequestBody Map<String,String> param){
        QueryWrapper<SpecialValue> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("recommend_goods");
        SpecialValue goodsJson=specialValueMapper.selectOne(queryWrapper);
        List<String> ids= JSONArray.parseArray(goodsJson.getRecommendGoods(),String.class);
        ids.add(param.get("id"));
        specialValueMapper.saveRecommendGoods(JSON.toJSONString(ids));
        return Result.OK();
    }
}
